<template>
    <f7-page class="common-page has-bottom-btns">
        <f7-navbar>
            <f7-nav-left>
                <f7-link back icon-material="chevron_left" force></f7-link>
            </f7-nav-left>
            <f7-nav-title>进场验收</f7-nav-title>
            <f7-nav-right></f7-nav-right>
        </f7-navbar>
        <div class="common-page-content">
            <v-accordion title="基本信息">
                <van-form class="basic-form" ref="form" :readonly="!canEdit">
                    <van-field v-model="models.model.recordCode" required
                        :rules="[{ required: true, message: '请输入车牌号/设备号' }]" label="车牌号/设备号" placeholder="请输入"
                        label-width="100" input-align="right">
                        <template #button v-if="canEdit">
                            <span class="choose-span" @click="showEquip = true">选择</span>
                        </template>
                    </van-field>
                    <van-field v-model="models.model.equipmentType" readonly class="choose-box" required
                        :rules="[{ required: true, message: '请选择设备类型' }]" label="设备类型" placeholder="请选择"
                        :right-icon="canEdit ? 'arrow' : ''" label-width="100" input-align="right"
                        @click-input="canEdit ? showEquipType = true : ''">
                        <template #input>
                            <span>{{
                    models.model.equipmentType
                    | DictItem(controlData.mobileEquipmentType)
                }}</span>
                        </template>
                    </van-field>
                </van-form>
            </v-accordion>
            <v-picture-list :props="{ name: 'customName' }" :disabled="!canEdit" listName="list1"
                title="设备质保资料" typeCode="EQM_MOBILE_ZBZL" :dataKey="models.model.registerId"
                @onAfterQuery="(val) => (list1 = val)" ref="list1" @checkItem="checkItem"></v-picture-list>
            <v-picture-list :props="{ name: 'customName' }" :disabled="!canEdit" listName="list2"
                title="关键部位检查" typeCode="EQM_MOBILE_GJBWJC" :dataKey="models.model.registerId"
                @onAfterQuery="(val) => (list2 = val)" ref="list2" @checkItem="checkItem"></v-picture-list>
            <v-picture-list :props="{ name: 'customName' }" :disabled="!canEdit" listName="list3" title="验收挂牌"
                typeCode="EQM_MOBILE_YSGP" :dataKey="models.model.registerId" @onAfterQuery="(val) => (list3 = val)"
                ref="list3" @checkItem="checkItem">
                <template v-slot:nameRight="slotProps">
                    <span v-if="slotProps.bizType == 'YSB'"
                        style="color: #61677a; font-size: 13px; font-weight: 400">（每次进场要重新办理验收挂牌）</span>
                </template>
            </v-picture-list>
            <v-picture-list :props="{ name: 'customName' }" :disabled="!canEdit" listName="list4"
                title="大型移动机械设备安装检查" typeCode="EQM_MOBILE_AZJC" :dataKey="models.model.registerId"
                @onAfterQuery="(val) => (list4 = val)" ref="list4" @checkItem="checkItem"></v-picture-list>
            <v-accordion title="操作记录" v-if="history.length">
                <v-workflow-list :data="history"></v-workflow-list>
            </v-accordion>
        </div>
        <!-- 选择设备 -->
        <device-popup v-model="showEquip" :equipmentTypeList="controlData.mobileEquipmentType" :engineeId="engineeId" useStatus="exit"
            url="/app/equipment/eqmMobileRegister/query" @save="sureDevice"></device-popup>
        <!-- 选择设备类型 -->
        <van-action-sheet v-model="showEquipType" :actions="controlData.mobileEquipmentType"
            @select="onSelectTypeDone" />
        <f7-toolbar position="bottom" no-shadow class="fff" v-if="(canEdit || canCheck) && !showEquipType">
            <!-- 施工单位填写 -->
            <template v-if="canEdit">
                <f7-button fill class="submit-btn plain-btn" @click="saveDraft()">保存</f7-button>
                <f7-button fill class="submit-btn" @click="fnSubmit()">提交</f7-button>
            </template>
            <!-- 监理单位审核 -->
            <template v-else-if="canCheck">
                <f7-button fill class="submit-btn plain-btn" @click="fnCheck('reject')">退回</f7-button>
                <f7-button fill class="submit-btn" @click="fnCheck('pass')">通过</f7-button>
            </template>
        </f7-toolbar>
        <!-- 审核意见 -->
        <v-popup-opinion v-model="showPinion" ref="opinion" @save="saveDetects()" :selectUser="selectUser">
        </v-popup-opinion>
    </f7-page>
</template>

<script>
import DevicePopup from "../components/DevicePopup.vue";
import controller from "@/libs/framework/workflowController";
export default class instance extends controller {
    disableCache() {
        return true;
    }
    onBeforeInit() {
        this.urls = {
            model: ["/equipment/eqmMobileRegister/workflow/getWorkflowViewModel"],
            processSave: "/equipment/eqmMobileRegister/workflow/processSave",
        };
    }
    onInit() {
        this.context.engineeId = this.$f7route.query.engineeId;
        this.$params.appCode = "mobileMachineryReg";
    }
    onAfterQuery(type, isSuccess, result) {
        if (type == "form") {
            this.context.pageAction = result.pageAction;
        }
        return result;
    }
    onAfterSave(isSuccess, result) {
        if (isSuccess) {
            if (result.parameters && result.parameters.models)
                this.context.models.model = result.parameters.models.model;
        }
    }
    mixin() {
        return {
            data() {
                return {
                    engineeId: "",
                    controlData: {
                        mobileEquipmentType: [],
                        workflow: {}
                    },
                    models: {
                        model: {}
                    },
                    selectUser: {
                        selectComment: null,
                        comment: null,
                        comments: [],
                        tran: [],
                        activity: "",
                        users: [],
                    },
                    equipmentTypeList: [],
                    pageAction: "",
                    showEquip: false,// 选择设备
                    showEquipType: false, // 选择设备类型
                    showPinion: false,// 审核
                    auditType: '',// 审核类型 通过 退回
                };
            },
            components: {
                DevicePopup,
            },
            computed: {
                // 是否可以编辑
                canEdit() {
                    if (this.pageAction != "view" && this.controlData.isConOrg && !this.controlData.workflow.isFormReadOnly) {
                        // 施工单位
                        return true;
                    }
                    return false;
                },
                // 是否可审核 监理单位
                canCheck() {
                    if (this.pageAction == "edit" && this.controlData.isSupOrg) {
                        return true;
                    }
                    return false;
                },
                // 操作记录
                history() {
                    if (this.controlData.workflow && this.controlData.workflow.history && this.controlData.workflow.history.length > 0) {
                        return this.controlData.workflow.history
                    } else {
                        return []
                    }
                },
            },
            methods: {
                // 保存草稿
                saveDraft() {
                    if (!this.models.model.recordCode) {
                        return this.$toast("请输入或选择车牌号/设备编号");
                    }
                    if (!this.models.model.equipmentType) {
                        return this.$toast("请选择设备类型");
                    }
                    this.models.model.engineeId = this.engineeId;
                    this.super.save(this.models, false, "", true, "保存成功");
                },
                // 提交
                fnSubmit() {
                    let flag1 = this.$refs.list1.getUploadedCount();
                    let flag2 = this.$refs.list2.getUploadedCount();
                    let flag3 = this.$refs.list3.getUploadedCount();
                    let flag4 = this.$refs.list4.getUploadedCount();
                    if (!flag1 || !flag2 || !flag3 || !flag4)
                        return this.$toast("请上传必传设备进场附件");
                    this.$refs.form
                        .validate()
                        .then((res) => {
                            this.models.model.engineeId = this.engineeId;
                            this.send();
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                },
                // 无此项 处理函数
                checkItem(index, item) {
                    this.$util
                        .getPromise(`/admin/attachmentFormDetail/saveAllowNone`, {
                            caseId: this.models.model.registerId,
                            dicId: item.id,
                            type: item.isNil ? 1 : 0,
                        })
                        .then((r) => {
                            if (!r.success) {
                                this.$toast("勾选失败！");
                            }
                        });
                },
                //选择设备完成
                sureDevice(result) {
                    if (result.registerId) {
                        this.models.model.recordCode = result.recordCode;
                        this.models.model.equipmentType = result.equipmentType;
                        this.models.model.engineeId = result.engineeId;
                        if(this.pageAction == 'create'){
                            this.reloadRegister(result)
                        }else{
                            this.handleCopyAttachment(result);
                        }
                    }
                },
                // 选择设备之后 要重新刷新 进场Id
                reloadRegister(oldRegister) {
                    this.$f7.request.post(
                        `/equipment/eqmMobileRegister/workflow/getWorkflowViewModel`,
                        {
                            engineeId: this.engineeId,
                            action: 'processStart',
                            appCode: 'mobileMachineryReg',
                            version: 1,
                            isDelay: false
                        },
                        (r) => {
                            r = JSON.parse(r);
                            if (r && r.success) {
                                this.models.model.registerId = r.models.model.registerId;
                                this.handleCopyAttachment(oldRegister);
                            }
                        },
                        (err) => { reject() }
                    );
                },
                // 选择一个退场的设备后 要将之前设备的附件全部复制一套到新的进场
                handleCopyAttachment(result) {
                    let pendingTasks1 = this.$refs.list1.list.length;
                    let pendingTasks2 = this.$refs.list2.list.length;
                    let pendingTasks4 = this.$refs.list4.list.length;

                    this.$refs.list1.list.forEach(item => {
                        this.copyAttachment(result.registerId, item.bizType, this.models.model.registerId, item.bizType).then(r => {
                            pendingTasks1--;
                            if (pendingTasks1 == 0) {
                                this.$refs.list1.getFileList(true);
                            }
                        })
                    });
                    this.$refs.list2.list.forEach(item => {
                        this.copyAttachment(result.registerId, item.bizType, this.models.model.registerId, item.bizType).then(r => {
                            pendingTasks2--;
                            if (pendingTasks2 == 0) {
                                this.$refs.list2.getFileList(true);
                            }
                        })
                    });
                    this.$refs.list4.list.forEach(item => {
                        this.copyAttachment(result.registerId, item.bizType, this.models.model.registerId, item.bizType).then(r => {
                            pendingTasks4--;
                            if (pendingTasks4 == 0) {
                                this.$refs.list4.getFileList(true);
                            }
                        })
                    });
                },
                // 复制附件
                copyAttachment(oldDataKey, oldBizType, newDataKey, newBizType, listName) {
                    return new Promise((resolve, reject) => {
                        this.$f7.request.post(
                            `/app/mobileApi/base/fileupload/copyAttachment`, {
                            oldDataKey: oldDataKey,
                            oldBizType: oldBizType,
                            newDataKey: newDataKey,
                            newBizType: newBizType
                        },
                            (r) => {
                                r = JSON.parse(r);
                                if (r && r.success) {
                                    resolve('wqeqweqweqwe');
                                } else {
                                    reject();
                                }
                            },
                            (err) => {
                                reject(err)
                            }
                        );
                    })

                },
                // 选择设备类型
                onSelectTypeDone(equipItem) {
                    this.models.model.equipmentType = equipItem.code;
                    this.showEquipType = false;
                },
                // 审核
                fnCheck(type) {
                    this.auditType = type;
                    this.selectUser.comment = "";
                    this.showPinion = true;
                },
                // 审核提交
                saveDetects() {
                    if (this.auditType == 'pass') {// 通过
                        this.showPinion = false
                        this.send();
                    } else {// 退回
                        this.$f7.preloader.show();
                        this.super.fnBackJump(
                            this.selectUser.comment,
                            (result) => {
                                this.$f7.preloader.hide();
                                if (result.success) {
                                    this.showPinion = false
                                    this.refreshData('退回成功')
                                } else {
                                    this.$f7.dialog.alert(result.message)
                                }
                            },
                            (e) => {
                                this.$f7.preloader.hide();
                            },
                            'usertask1'
                        )
                    }
                },
                refreshData(msg) {
                    this.$f7.dialog.alert(msg, () => {
                        this.$f7.popup.close();
                        this.$f7.views.current.router.back({ force: true })
                    })
                },
            },
        };
    }
}
</script>


<style lang="less" scoped>
@import url("../../../../../assets/css/commonPage.less");
@deep: ~">>>";

@{deep} .v-workflow-list {
    padding: 0 16px;
}

@{deep}.accordion .accordion-item>.item-link>.item-content {
    padding-left: 16px !important;
}

@{deep}.van-cell {
    display: flex;
    align-items: center;
}

@{deep}.accordion.accordion-list {
    background-color: #fff;
    margin-bottom: 10px;
}

.basic-form {
    .choose-span {
        display: inline-block;
        padding-left: 16px;
        height: 15px;
        line-height: 15px;
        font-size: 13px;
        color: #3385ff;
        border-left: 1px solid #d7dce4;
    }

    @{deep}.van-field__control {
        font-size: 13px;
    }
}
</style>
